﻿using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
using NHibernate.Expression;

namespace MyMessenger.Core.Services.Impl
{
    public class MessageService : IMessageService
    {
        public Messege AddMessage(User from, User toUser, string text)
        {
            Messege msg = new Messege();
            msg.FromUser = from;
            msg.Text = text;
            msg.ToUser = toUser;
            msg.Time = DateTime.Now;
            ActiveRecordMediator<Messege>.SaveAndFlush(msg);
            return msg;
        }

        private static DetachedCriteria GetUserMessegeCriteria(User u, int lastMsgId)
        {
            DetachedCriteria crit = DetachedCriteria.For<Messege>();
            AbstractCriterion ex;

            ex = Expression.Eq("FromUser", u);
            ex = Expression.Or(ex, Expression.Eq("ToUser", u));
            ex = Expression.Or(ex, Expression.IsNull("ToUser"));

            if (lastMsgId>0)
                crit.Add(Expression.Gt("Id", lastMsgId));

            crit.Add(ex);
            crit.AddOrder(Order.Asc("Id"));
            return crit;
        }

        public Messege[] GetAllMessagesToUser(User u)
        {
            return GetNewMessages(u, 0);
        }

        public Messege[] GetNewMessages(User u, int lastMsgId)
        {
            DetachedCriteria crit = GetUserMessegeCriteria(u, lastMsgId);            
            return ActiveRecordMediator<Messege>.FindAll(crit);
        }
    }
}
